<template>
  <div class="dashboard-editor-container">
    <el-card>
      <el-tabs v-model="GroupBy">
        <el-tab-pane label="默认" :name="0"> </el-tab-pane>
      </el-tabs>
      <div
        class="table-wrapper"
        :style="{ minHeight: `calc(${computedHeight}px + ${verticalMove}px)` }"
      >
        <el-space class="flex items-center justify-between my-1">
          <div class="text-[16px] flex items-center gap-4">
            <div class="flex items-center rounded-full">
              <span class="font-bold">销售单号：</span>
              <div class="self-end">
                <span class="font-bold" v-if="saleOrderInfo.TOrderCode">
                  {{ saleOrderInfo.TOrderCode }}
                </span>
                <el-text v-else class="mx-1" type="info"
                  >请选择或者创建销售单</el-text
                >
              </div>
            </div>
            <div class="flex items-center">
              <span class="whitespace-nowrap font-bold">注册号码：</span>
              <el-input disabled></el-input>
            </div>
            <el-button type="primary" round plain @click="majorAdd"
              >+ 新增总单</el-button
            >
            <el-button
              v-if="saleOrderInfo.TOrderCode"
              type="info"
              round
              plain
              :icon="Delete"
              @click="handleDelete"
            >
              清空</el-button
            >
            <!-- <el-button type="default" @click="handleDelete"> 清空</el-button> -->
          </div>

          <!-- <div class="flex gap-4 items-center">
            <div>
              <el-select v-model="searchColValue" filterable class="w-30" placeholder="搜索列" clearable
                @change="handleColSelect">
                <el-option v-for="item in columns" :key="item.AttrId" :label="item.AttrName" :value="item.AttrName">
                </el-option>
              </el-select>
            </div>
            <div class=relative>
              <el-button-group>
                <el-button type="primary" plain :icon="DArrowLeft" @click="handleTableScroll('d-left')"></el-button>
                <el-button type="primary" plain :icon="ArrowLeft" @click="handleTableScroll('left')"></el-button>
                <el-button type="primary" plain :icon="Aim" @click="handleTableScroll('center')"></el-button>
                <el-button type="primary" plain :icon="ArrowRight" @click="handleTableScroll('right')"></el-button>
                <el-button type="primary" plain :icon="DArrowRight" @click="handleTableScroll('d-right')"></el-button>
              </el-button-group>
              <div class="scroll-status-bar rounded absolute w-[100%] bg-gray-200 h-[3px] bottom-[-6px]"></div>
            </div>
            <div>
              <el-popover>
                <template #default>
                  <div class="text-center">同步属性配置</div>
                </template>
<template #reference>
                  <el-button type="primary" link :icon="Setting" class="text-lg" @click="syncOrderAttrs">
                  </el-button>
                </template>
</el-popover>
</div>
</div> -->
        </el-space>
        <el-form inline class="mt">
          <el-form-item label="客户名称" required>
            <el-select v-model="customer" style="width: 100px">
              <el-option
                v-for="(item, index) in customerList"
                :key="index"
                :label="item.UserName"
                :value="item.UserName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="代理品牌" required>
            <el-select v-model="brandName" style="width: 100px">
              <el-option
                v-for="(item, index) in brandList"
                :key="index"
                :label="item.BrandName"
                :value="item.BrandName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品类型" required>
            <el-select v-model="seriesId" style="width: 100px">
              <el-option
                v-for="item in seriesList"
                :key="item.SeriesId"
                :label="item.SeriesName"
                :value="item.SeriesId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交货时间" required>
            <el-date-picker
              v-model="deliveryTime"
              style="width: 140px"
              type="date"
              prefixIcon=""
              format="YYYY年MM月DD日"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="交货时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="float-right">
            <div class="flex gap-4 items-center">
              <div>
                <el-select
                  v-model="searchColValue"
                  filterable
                  class="w-30"
                  placeholder="搜索列"
                  clearable
                  @change="handleColSelect"
                >
                  <el-option
                    v-for="item in columns.filter((item) => item.IsVisible)"
                    :key="item.AttrId"
                    :label="item.AttrName"
                    :value="item.AttrName"
                  >
                  </el-option>
                </el-select>
              </div>
              <div class="relative">
                <el-button-group>
                  <el-button
                    type="primary"
                    plain
                    :icon="DArrowLeft"
                    @click="handleTableScroll('d-left')"
                  ></el-button>
                  <el-button
                    type="primary"
                    plain
                    :icon="ArrowLeft"
                    @click="handleTableScroll('left')"
                  ></el-button>
                  <el-button
                    type="primary"
                    plain
                    :icon="Aim"
                    @click="handleTableScroll('center')"
                  ></el-button>
                  <el-button
                    type="primary"
                    plain
                    :icon="ArrowRight"
                    @click="handleTableScroll('right')"
                  ></el-button>
                  <el-button
                    type="primary"
                    plain
                    :icon="DArrowRight"
                    @click="handleTableScroll('d-right')"
                  ></el-button>
                </el-button-group>
                <div
                  class="scroll-status-bar rounded absolute w-[100%] bg-gray-200 h-[3px] bottom-[-6px]"
                ></div>
              </div>
              <div>
                <el-popover>
                  <template #default>
                    <div class="text-center">同步属性配置</div>
                  </template>
                  <template #reference>
                    <el-button
                      type="primary"
                      link
                      :icon="Setting"
                      class="text-lg"
                      @click="syncOrderAttrs"
                    >
                    </el-button>
                  </template>
                </el-popover>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <!-- :height=" computedHeight + verticalMove" -->
        <el-popover
          ref="popoverRef"
          width="fit-content"
          trigger="click"
          title="影响字段"
          virtual-triggering
          :visible="popoverVisible"
          :virtual-ref="inputRefs[currentInput]"
        >
          <template #title>title</template>
          <div>
            <div v-if="popoverInfo.computes.length !== 0" class="font-bold">
              计算属性
            </div>
            <div
              v-for="(compute, index) in popoverInfo.computes"
              :key="index"
              class="ml-1"
            >
              <div>
                <span>
                  {{ compute.target }}
                </span>
                <span class="text-bold mx-1">=</span>
                <span
                  v-for="(item, inIndex) in compute.formulaEles"
                  :key="inIndex"
                  :class="{
                    'font-bold text-[#1d4ed8]':
                      getAttrKey(item) == currentColumnKey,
                    'mr-1': true,
                  }"
                  >{{ item }}</span
                >
                <span class="mx-1">=</span>
                <span class="font-bold">{{ compute.targetValue }}</span>
              </div>
            </div>
            <div v-if="popoverInfo.offers.length !== 0" class="font-bold mt-1">
              报价方式
            </div>
            <div
              v-for="(offer, index) in popoverInfo.offers"
              :key="index"
              class="ml-1"
            >
              <div>
                <span> 结算金额{{ offer.target && `(${offer.target})` }}</span>
                <span class="mx-1">=</span>
                <span
                  v-for="(item, inIndex) in offer.formulaEles"
                  :key="inIndex"
                  :class="{
                    'font-bold text-[#1d4ed8]':
                      getAttrKey(item) == currentColumnKey,
                    'mr-1': true,
                  }"
                  >{{ item }}</span
                >
                <span class="text-bold mx-1">=</span>
                <span class="font-bold">{{ offer.targetValue }}</span>
              </div>
            </div>
          </div>
        </el-popover>
        <el-table
          v-loading="loading"
          ref="tableRef"
          :data="dataList"
          :row-style="addRowStyle"
          :maxHeight="tableHeight + verticalMove"
          row-key="OrderCode"
          default-expand-all
          @selection-change="handleRowCheckBox"
        >
          <!-- :expand-row-keys="expandedRowKeys"
          @expand-change="expandOpen" -->
          <!-- <el-table-column type="expand" fixed="left">
            <template #default="{ row }">
              <div class="pl-14 py-4 bg-slate-100">
                <div class="flex items-center w-fit whitespace-nowrap">
                  <div class="font-bold text-[17px]">价格说明：</div>
                  <div>门：</div>
                  <el-input
                    v-model="row.doorPrice"
                    type="number"
                    @keyup.stop="(e) => e.preventDefault()"
                  ></el-input>
                  <div>，内包边：</div>
                  <el-input
                    v-model="row.PackageAmount"
                    type="number"
                  ></el-input>
                  <div>，合计：</div>
                  <el-input v-model="row.TotalAmount" type="number"></el-input>
                </div>
                <div class="flex mt-2">
                  <div class="font-bold text-[17px]">附图：</div>
                  <ImageUpload v-model="row.Picture" :limit="10"></ImageUpload>
                </div>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column type="selection" reserve-selection fixed="left">
          </el-table-column>
          <el-table-column type="expand" width="20">
            <template #default="scope">
              <div
                class="flex items-center gap-12"
                v-if="
                  getSpecificSetting(
                    scope.row.SeriesId,
                    'Remark_Money',
                    'IsVisible'
                  ) || getSpecificSetting(scope.row.SeriesId, '备注', 'Remark')
                "
              >
                <div
                  class="flex items-center"
                  v-if="
                    getSpecificSetting(
                      scope.row.SeriesId,
                      'Remark',
                      'IsVisible'
                    )
                  "
                  :style="{
                    marginLeft: tableLeft + 'px',
                  }"
                >
                  <span> 备注： </span>
                  <el-input
                    class="w-100"
                    type="textarea"
                    autosize
                    placeholder="备注"
                    @input="changeEvent(scope.row, scope.$index, 'Remark')"
                    v-model="scope.row.Remark"
                  ></el-input>
                </div>
                <div
                  class="flex items-center"
                  v-if="
                    getSpecificSetting(
                      scope.row.SeriesId,
                      'Remark_Money',
                      'IsVisible'
                    )
                  "
                >
                  <span class="w-20"> 价格说明： </span>
                  <el-input
                    type="textarea"
                    autosize
                    class="w-100"
                    placeholder="价格说明"
                    @input="
                      changeEvent(scope.row, scope.$index, 'Remark_Money')
                    "
                    v-model="scope.row.Remark_Money"
                  ></el-input>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="产品类型" width="130" fixed="left">
            <template #header>
              <div class="font-bold">
                <i class="text-red-500 mr-1">*</i>产品类型
              </div>
            </template>
            <template #default="{ row }">
              <el-select
                v-model="row.SeriesId"
                placeholder="请选择产品类型"
                @change="onProductChange"
              >
                <el-option
                  v-for="item in seriesList"
                  :key="item.SeriesId"
                  :label="item.SeriesName"
                  :value="item.SeriesId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column> -->
          <el-table-column
            v-for="(item, index) in columns.filter(
              (e) =>
                ![
                  '价格说明',
                  '备注',
                  '数量-左',
                  '数量-右',
                  '门头',
                  '门柱',
                  '附图',
                  '门总宽',
                  '门总高',
                  '墙体厚度',
                ].includes(e.AttrName)
            )"
            :key="index"
            :width="getHighColWidth(item.AttrName) + 3 + 'px'"
            :fixed="fixMap[item.FixType].value"
            :class-name="columnBgColor"
            :prop="item.AttrKeyName"
            align="center"
          >
            <template #header>
              <div
                :class="{
                  'font-bold': true,
                  'bg-[#ff9632]': searchColValue == item.AttrName,
                }"
              >
                <template v-if="item.AttrName == '数量'">
                  <div>
                    <div>
                      {{
                        customAttrKeyName(
                          orderAttrsMap2[item.AttrKeyName] || item.AttrName
                        )
                      }}
                    </div>
                    <div class="flex justify-center gap-6">
                      <div>左</div>
                      <div>右</div>
                    </div>
                  </div>
                </template>
                <template v-else-if="item.AttrName == '规格'">
                  <div>
                    <div>规格</div>
                    <div class="flex justify-center gap-6">
                      <div>高</div>
                      <div>宽</div>
                      <div>墙体</div>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <span>
                    {{
                      customAttrKeyName(
                        orderAttrsMap2[item.AttrKeyName] || item.AttrName
                      )
                    }}
                  </span>
                </template>
              </div>
            </template>
            <!-- 关键代码 -->
            <template #default="scope">
              <template v-if="item.AttrName == '数量'">
                <div class="flex gap-1">
                  <el-input
                    v-model="scope.row.Count1"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                  <el-input
                    v-model="scope.row.Count2"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                </div>
              </template>
              <template v-else-if="item.AttrName == '规格'">
                <div class="flex gap-1">
                  <el-input
                    v-model="scope.row.Height_Total"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                  <el-input
                    v-model="scope.row.Width_Total"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                  <el-input
                    v-model="scope.row.Tickness_Wall"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                </div>
              </template>
              <template v-else-if="item.AttrName == '门头门柱'">
                <div class="flex gap-1">
                  <el-input
                    v-model="scope.row.DoorHeader"
                    placeholder="门头"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                  <el-input
                    v-model="scope.row.DoorPost"
                    placeholder="门柱"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                  ></el-input>
                </div>
              </template>
              <template v-else>
                <template
                  v-if="
                    getSpecificSetting(
                      scope.row.SeriesId,
                      item.AttrKeyName,
                      'IsVisible'
                    )
                  "
                >
                  <el-input
                    v-if="
                      getSpecificSetting(
                        scope.row.SeriesId,
                        item.AttrKeyName,
                        'InputType'
                      ) == 1
                    "
                    v-model="scope.row[item.AttrKeyName]"
                    :id="'input-' + scope.$index + item.AttrKeyName"
                    :ref="
                      (el) => setInputRef(el, scope.$index + item.AttrKeyName)
                    "
                    :type="
                      inputModeMap[
                        getSpecificSetting(
                          scope.row.SeriesId,
                          item.AttrKeyName,
                          'InputType2'
                        )
                      ].value
                    "
                    :disabled="
                      getSpecificSetting(
                        scope.row.SeriesId,
                        item.AttrKeyName,
                        'inputType'
                      ) == 3
                    "
                    :input-style="{
                      border: 'none',
                    }"
                    @click="clickEvent"
                    @focus="
                      focusEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                    @blur="blurEvent(scope.row, scope.$index, item.AttrKeyName)"
                    @input="
                      changeEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                    @keydown="
                      keyupEvent(
                        $event,
                        scope.row,
                        scope.$index,
                        item.AttrKeyName
                      )
                    "
                    :placeholder="`${customAttrKeyName(item.AttrName)}`"
                  ></el-input>
                  <el-select
                    suffix-icon=""
                    v-if="
                      getSpecificSetting(
                        scope.row.SeriesId,
                        item.AttrKeyName,
                        'InputType'
                      ) == 0
                    "
                    :id="'input-' + scope.$index + item.AttrKeyName"
                    v-model="scope.row[item.AttrKeyName]"
                    @change="
                      selectEvent(scope.row, scope.$index, item.AttrKeyName)
                    "
                    @keydown.stop="
                      keyupEvent(
                        $event,
                        scope.row,
                        scope.$index,
                        item.AttrKeyName
                      )
                    "
                    @visible-change="
                      selectKeyJump(
                        $event,
                        scope.row,
                        scope.$index,
                        item.AttrKeyName
                      )
                    "
                  >
                    <el-option
                      v-for="p in getSpecificSetting(
                        scope.row.SeriesId,
                        item.AttrKeyName,
                        'AttrValue'
                      )
                        .replaceAll('，', ',')
                        .split(',')"
                      :key="p"
                      :label="p"
                      :value="p"
                    >
                    </el-option>
                  </el-select>
                  <el-button
                    type="primary"
                    :icon="Upload"
                    link
                    v-else-if="
                      getSpecificSetting(
                        scope.row.SeriesId,
                        item.AttrKeyName,
                        'InputType'
                      ) == 2
                    "
                    @click="
                      openPictureModal(scope.$index, scope.column.property)
                    "
                    >上传图片
                    <span
                      v-if="
                        scope.row.AttatchUrl.split(',').filter(Boolean)
                          .length !== 0
                      "
                      class="ml-1"
                      >({{
                        scope.row.AttatchUrl.split(",").filter(Boolean).length
                      }})</span
                    >
                  </el-button>
                </template>
                <template v-else>
                  <div></div>
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="附图" align="center">
            <template #default="{ row, $index }">
              <div class="flex justify-center gap-2">
                <template v-if="row.AttatchUrl">
                  <!-- v-for="src in row.AttatchUrl.split(',')" -->
                  <el-image
                    class="w-10 h-10"
                    v-for="src in row.AttatchUrl.split(',').slice(0, 1)"
                    :key="src"
                    :src="src"
                    @click="handleImageClick(src)"
                  ></el-image>
                  <template v-if="row.AttatchUrl.split(',').length > 1">
                    <el-button
                      type="primary"
                      link
                      :icon="Picture"
                      @click="openPictureModal($index, 'AttatchUrl')"
                      >+{{ row.AttatchUrl.split(",").length - 1 }}</el-button
                    >
                  </template>
                  <template v-if="row.AttatchUrl.split(',').length < 2">
                    <el-button
                      type="primary"
                      link
                      :icon="Upload"
                      @click="openPictureModal($index, 'AttatchUrl')"
                    ></el-button>
                  </template>
                </template>
                <template v-else>
                  <el-button
                    type="primary"
                    link
                    :icon="Upload"
                    @click="openPictureModal($index, 'AttatchUrl')"
                    >上传</el-button
                  >
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="88" align="center" fixed="right">
            <template #default="scope">
              <el-button
                type="success"
                size="small"
                circle
                :icon="Plus"
                @click="handleOperate('add', scope.$index)"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                circle
                :icon="Minus"
                @click="handleOperate('delete', scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-space class="flex justify-between my-1 mr-4 font-bold">
          <el-space> 销售单摘要 <el-input></el-input> </el-space>
          <div class="flex gap-2">
            <div>
              本单合计:
              <span class="text-red mx-1 text-lg">{{
                formatPrice(totalOrderMoney)
              }}</span
              >元
            </div>
            <div>
              <el-button type="primary" @click="handleAdd">+ 增加</el-button>
              <el-button type="primary" @click="handleSave">
                <svg-icon class="mr-1" icon-class="save" />
                保存</el-button
              >
              <el-button type="success" @click="handleSubmit">
                <el-icon><Select /></el-icon>提交</el-button
              >
            </div>
          </div>
        </el-space>
        <pagination
          v-model:page="pageNum"
          v-model:limit="pageSize"
          v-show="dataList.length > 0"
          :total="dataList.length"
          @pagination="
            dataList = orderStore.getOrderDataSlice({ pageSize, pageNum })
          "
        />
      </div>
      <div
        :class="`layout-divider ${dividerActive ? 'divider-active' : ''}`"
        @mousedown.prevent="holdDown"
      >
        <Sort
          :class="`layout-divider-icon ${
            dividerActive ? 'divider-active-icon' : ''
          }`"
        />
      </div>

      <el-tabs v-model="summaryBy" row-key="TOrderId">
        <el-tab-pane label="销售单列表" :name="0">
          <el-row :gutter="2">
            <el-col :span="19">
              <el-space>
                <el-button
                  class="bg-[#1e8c68] my-btn-hover"
                  type="success"
                  :icon="Printer"
                  @click="handlePrint"
                  >批量打印</el-button
                >
                <el-button type="danger" disabled>批量提交生产</el-button>
              </el-space>

              <el-space
                style="
                  margin-top: 10px;
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <el-space>
                  <el-input
                    style="width: 100px"
                    placeholder="销售单编号、客户"
                  />
                  <el-select style="width: 100px"></el-select>
                  <el-date-picker
                    v-model="saleDate"
                    type="daterange"
                    class="w-[210px]"
                    value-format="YYYY-MM-DD"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                  />
                  <el-button type="primary" @click="getSaleData"
                    >搜索</el-button
                  >
                  <el-button type="info" plain @click="getSaleData"
                    >刷新</el-button
                  >
                </el-space>
                <el-space>
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox label="代办" value="todos" />
                    <el-checkbox label="全部订单" value="allOrders" />
                  </el-checkbox-group>
                  <el-button type="primary" plain @click="toDetailRecord"
                    >详情页录单</el-button
                  >
                  <el-button
                    type="danger"
                    plain
                    :icon="Delete"
                    circle
                    @click="handleDeleteUnsaved"
                  />
                  <el-button
                    type="info"
                    plain
                    :icon="Menu"
                    circle
                    @click="handleClick"
                  />
                </el-space>
              </el-space>
              <el-table
                ref="submitTableRef"
                :data="saleDataList"
                style="margin-top: 10px"
                highlight-current-row
                row-key="TOrderId"
                @row-click="handleRowClick"
                @select="handleRowSelect"
                v-loading="loading"
              >
                <el-table-column
                  type="selection"
                  reserve-selection
                  align="center"
                  width="55"
                />
                <el-table-column label="销售单号" prop="TOrderCode">
                  <template #defualt="scope">
                    <el-button type="primary" link>{{
                      scope.row.TOrderCode
                    }}</el-button></template
                  ></el-table-column
                >
                <el-table-column label="订单编号" width="120">
                  <template #default="scope">
                    <div
                      v-for="(item, index) in scope.row.OrderCodeStr.split(',')"
                      :key="index"
                    >
                      {{ item }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="工单编号"></el-table-column>
                <el-table-column
                  label="商品类型"
                  prop="TField1"
                ></el-table-column>
                <el-table-column
                  label="客户"
                  prop="CustomerName"
                ></el-table-column>
                <el-table-column
                  label="子客户"
                  prop="TSubCustomerNames"
                ></el-table-column>
                <el-table-column
                  label="创建时间"
                  prop="TOrderSDate"
                  :formatter="
                    (row) => timeStampFormatter(row.TOrderSDate, true)
                  "
                ></el-table-column>
                <el-table-column
                  label="合计金额"
                  prop="TPrice"
                ></el-table-column>
                <el-table-column
                  label="樘数"
                  prop="TPieceCount"
                ></el-table-column>
                <el-table-column
                  label="接单员"
                  prop="SalesmanName"
                ></el-table-column>
                <el-table-column label="状态" prop="Status">
                  <template #default="scope">
                    <span
                      :class="{
                        'inline-block w-[8px] h-[8px]  rounded-[50%] mr-[4px]': true,
                        'bg-gray': !scope.row.IsFinish,
                        'bg-green-600': scope.row.IsFinish,
                      }"
                    ></span
                    >{{ scope.row.IsFinish ? "已确认" : "未确认" }}
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="5" class="h-full overflow-auto">
              <div
                class="p-2 flex items-center"
                v-for="(item, index) in attachedPictureList"
                :key="index"
              >
                <div
                  ref="paste"
                  class="relative w-15 h-15 rounded-1 text-center leading-17 cursor-pointer mr-4"
                  style="border: 1px solid #999"
                >
                  <div
                    :id="'abc' + index"
                    class="w-full h-full caret-transparent active:opacity-80"
                    @mousedown="pasteImage($event, item, index)"
                    @contextmenu.prevent.stop="(e) => false"
                  >
                    <el-image
                      v-if="item.src"
                      :src="item.src"
                      class="w-full h-full my-el-image"
                      fit="scale-down"
                      :preview-src-list="[item.src]"
                    >
                    </el-image>
                    <Plus size="5" v-else />
                    <!-- <span v-else class="my-span">上传</span> -->
                  </div>
                  <el-icon
                    v-show="item.src"
                    class="text-lg absolute right-[-4px] bottom-[-4px] z-10 bg-white p-[1px] rounded-[50%]"
                    @click="handlePreviewImg(item.src)"
                  >
                    <ZoomIn />
                  </el-icon>
                  <!-- <Plus size="6" /> -->
                </div>
                <el-input
                  class="flex-1"
                  :placeholder="
                    index == attachedPictureList.length - 1
                      ? '请复制粘贴'
                      : '请截图复制粘贴'
                  "
                  @paste="handlePaste($event, index)"
                ></el-input>
                <!-- <el-select v-model="item.col" class="flex-1">
                  <el-option
                    v-for="(item, index) in attachedPictureCols"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select> -->
                <el-icon
                  v-if="index !== attachedPictureList.length - 1"
                  class="text-red-500 ml-2 text-lg cursor-pointer"
                  @click="handleDeleteImg(index)"
                >
                  <Delete />
                </el-icon>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="订单列表" :name="1"> </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog title="附图" width="700" v-model="pictureOpen">
      <ImageUpload v-model="pictureList" isOrigin />
      <template #footer>
        <el-button @click="pictureOpen = false">取 消</el-button>
        <el-button type="primary" @click="pictureConfirm">确 定</el-button>
      </template>
    </el-dialog>
    <input ref="imgUploader" accept="image/*" class="hidden" type="file" />
  </div>
</template>
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  DArrowLeft,
  Picture,
  DArrowRight,
  Mouse,
  ArrowLeft,
  ArrowRight,
  Aim,
  Delete,
  Menu,
  Minus,
  Plus,
  Upload,
  ZoomIn,
  Printer,
  Setting,
  Refresh,
} from "@element-plus/icons-vue";
import { ClickOutside as vClickOutside } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";

import useOrderAttrStore from "@/store/modules/orderAttrs";
import useOrderDataStore from "@/store/modules/orderData";

import {
  orderAttrsMap2,
  getAttrKey,
  inputModeMap,
  fixMap,
  attachedPictureCols,
} from "@/utils/map";
import {
  formatPrice,
  evaluate,
  base64ToBlob,
  createUniqueString,
  getClipBoardImage,
  timeStampFormatter,
  blobToFile,
} from "@/utils";

import { attrNameReg, splitFormulaElements } from "@/utils/validate";
import { generateHexColor } from "@/utils/randomColor";

import { seriesQueryApi } from "@/api/order/series/index.js";
import {
  attrQueryApi,
  computeQueryApi,
  offerQueryApi,
} from "@/api/order/attr/index.js";
import {
  orderQueryApi,
  saleOrderQueryApi,
  saleOrderDetailApi,
  saleOrderAddApi,
  orderCodeApi,
  saleOrderRemoveApi,
  orderRemoveApi,
  saleOrderAddEmptyApi,
} from "@/api/order/manage/index.js";
import { uploadImg } from "@/api/upload.js";
import { brandQueryApi } from "@/api/order/brand/index.js";
import { customerQueryApi } from "@/api/order/customer/index.js";
import { flexColumnWidth } from "@/utils/flexCol.js";
import { nextTick } from "vue";

const GroupBy = ref(0);
const summaryBy = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const checkList = ref([]);
const tableRef = ref();
const expandedRowKeys = ref([]);
const pictureList = ref([]);
const pictureOpen = ref(false);
const tableLeft = ref(0);
// 客户名称下拉选
const customer = ref("");
const customerList = ref([]);
// 代理品牌下拉选
const brandName = ref();
// 产品系列下拉选
const seriesId = ref();
// 销售单保存-交货时间
const deliveryTime = ref();
const imgUploader = ref();
const currentImgIndex = ref(-1);
const submitTableRef = ref();

// columnBgColor用于检索列水平滚动表格，设置结果列的背景色，突出显示
const columnBgColor = ref("");
const searchColValue = ref("");
const router = useRouter();
const route = useRoute();
const orderAttrStore = useOrderAttrStore();
const orderStore = useOrderDataStore();
const productList = orderAttrStore.orderAttrs;
const attachedPictureList = ref([{ col: "", src: "" }]);
const scrollBarLeft = ref("0%");
const dataList = ref([]);

const saleDataList = ref([]);
const saleOrderInfo = ref({});
const currentSaleRow = ref({});
const unsavedWarnOff = ref(false);

const seriesList = ref([]);

const brandList = ref();
// 获取当前月份的第一天
const firstDayOfMonth = dayjs().startOf("month").format("YYYY-MM-DD");
// 获取当前月份的最后一天
const lastDayOfMonth = dayjs().endOf("month").format("YYYY-MM-DD");

const saleDate = ref([firstDayOfMonth, lastDayOfMonth]);
const loading = ref(false);
// 所有系列的属性都放在里面
const attrsList = ref({});
const computeList = ref({});
const offerList = ref({});
const currentColumnKey = ref("");
let currentTableIndex = "";
const columns = ref([]);
// 自定义列显示顺序
const customeSequence = [
  "结构",
  "门面款式",
  "数量",
  "规格",
  "含中下档高",
  "颜色",
  "开向",
  "包边",
  "铰链",
  "锁具",
  "拉手",
  "气窗",
  "下档",
  "门面",
  "门框",
  "门头门柱",
  "单价",
  "结算方式",
  "金额",
];
defineOptions({
  name: "Orders",
});
const totalOrderMoney = computed(() => {
  // 订单金额计算
  let sum = 0;
  dataList.value.forEach((item) => {
    sum += +item.Money_Total || 0;
  });
  return sum;
});
const popoverVisible = ref(false);
const inputRefs = ref({});
const popoverRef = ref({});
const currentInput = ref("");
const throttleTimer = ref(null);
const throttle = ref(true);
const popoverInfo = reactive({
  computes: [],
  offers: [],
});
let tempDataList = [];
let tempSaleDataList = [];
const allowDisappear = ref(true);
document.addEventListener("click", (_) => {
  if (
    allowDisappear.value &&
    (!document.activeElement.className.includes("popover") ||
      !document.activeElement.id.includes("input-"))
  )
    popoverVisible.value = false;
});
document.addEventListener("keyup", (_) => {
  if (
    allowDisappear.value &&
    (!document.activeElement.className.includes("popover") ||
      !document.activeElement.id.includes("input-"))
  )
    popoverVisible.value = false;
});
function setInputRef(el, key) {
  if (el) inputRefs.value[key] = el.ref;
}
function hanleClickOutSide(e) {
  popoverVisible.value = true;
  // unref(popoverRef).popperRef?.delayHide?.();
}
onMounted(() => {
  let dom = document.querySelector(".table-wrapper");
  computedHeight.value = dom.scrollHeight;
  try {
    getData();
  } catch (error) {}
  tableScroll();
  registerPaste();
  imgUploader.value.addEventListener("change", async (e) => {
    let [file] = imgUploader.value.files;
    const res = await uploadImg({ img: file, Name: file.name });
    attachedPictureList.value[currentImgIndex.value].src = res.name;
    const [row] = tableRef.value.getSelectionRows();
    row.AttatchUrl = attachedPictureList.value.map((e) => e.src).join(",");

    // let reader = new FileReader();
    // reader.readAsDataURL(file);
    // reader.onload = (res) => {
    //   const blob = base64ToBlob(res.target.result);

    //   attachedPictureList.value[currentImgIndex.value].src =
    //     URL.createObjectURL(blob);
    //   const [row] = tableRef.value.getSelectionRows();
    //   row.AttatchUrl = attachedPictureList.value.map((e) => e.src).join(",");
    // };
  });
});
function handlePrint1() {
  const selectionRows = tableRef.value.getSelectionRows();
  if (selectionRows.length > 0) {
    const routeData = router.resolve({
      path: "./print",
      query: {
        data: JSON.stringify(selectionRows),
        images: JSON.stringify(attachedPictureList.value),
        customer: customer.value,
      },
    });
    window.open(routeData.href, "_blank");
    // router.push({
    //   path: "./print",
    //   query: {
    //     data: JSON.stringify(selectionRows),
    //     images: JSON.stringify(attachedPictureList.value),
    //     customer: customer.value,
    //   },
    // });
  } else {
    ElMessage.warning("请勾选需要打印的订单");
  }
}
function tableScroll() {
  let mouseFlag = false,
    mouseStart = 0,
    startX = 0,
    tableBody;
  tableBody = tableRef.value.$refs.scrollBarRef.wrapRef;
  tableBody.addEventListener("scroll", (e) => {
    tableLeft.value = e.target.scrollLeft;
    scrollBarLeft.value =
      (e.target.scrollLeft / (e.target.scrollWidth - e.target.clientWidth)) *
        90 +
      "%";
  });
  tableRef.value.$el.addEventListener("mousedown", (e) => {
    // 拿到目标元素
    // 拖拽状态改为允许拖拽/鼠标样式修改公共方法
    setMouseFlag(true, tableBody);
    // 记录鼠标按下位置
    mouseStart = e.clientX;
    // 记录元素当前scrollLeft值
    startX = tableBody.scrollLeft;
    // 添加 dragstart 事件监听器
    document.addEventListener("dragstart", handleDragStart);
  });
  tableRef.value.$el.addEventListener("mousemove", (e) => {
    if (mouseFlag) {
      e.preventDefault();
      let offset = e.clientX - mouseStart;
      tableBody.scrollLeft = startX - offset;
    }
  });
  tableRef.value.$el.addEventListener("mouseup", () => {
    setMouseFlag(false, tableBody);
    // 移除 dragstart 事件监听器
    document.removeEventListener("dragstart", handleDragStart);
  });

  const handleDragStart = (e) => {
    // 取消默认的拖动效果
    e.preventDefault();
    setMouseFlag(false, tableBody);
  };

  const setMouseFlag = (flag, tableBody) => {
    mouseFlag = flag;
    if (tableBody) {
      tableBody.style.cursor = flag ? "grab" : "auto";
    }
  };
}
function banSelectEvent() {
  return false;
}
const tableScrollToColumn = (tableElement, columnIndex) => {
  let fixedNum = columns.value.filter((item) => item.FixType !== 0).length + 1;
  // const theTableRow = tableElement.scrollBarRef.wrapRef.querySelector(
  //   ".el-table__body tbody .el-table__row"
  // );
  const theTableColumns = tableElement.columns;
  let scrollLeft = 0;
  for (let i = fixedNum; i < theTableColumns.length; i++) {
    if (i == columnIndex || columnIndex < fixedNum) {
      break;
    }
    // scrollLeft += document.querySelector(
    //   `#${theTableColumns[i].id}`
    // ).offsetWidth;
    scrollLeft += theTableColumns[i].realWidth;
  }
  tableElement.scrollBarRef.wrapRef.scrollTo({
    left: scrollLeft,
    behavior: "smooth",
  });
  // tableElement.scrollBarRef.wrapRef.scrollLeft = scrollLeft;
};
async function getData() {
  loading.value = true;
  // 如果产品类型不存在，比如说被用户删掉了，那就换成别的
  const res = await seriesQueryApi();
  if (res.Data) seriesList.value = res.Data || [];
  for (let i = 0; i < seriesList.value.length; i++) {
    let s = seriesList.value[i];
    const res = await attrQueryApi({ seriesId: s.SeriesId, pageSize: 100 });
    attrsList.value["attrs" + s.SeriesId] = res.Data || [];
    const res2 = await computeQueryApi({
      seriesId: s.SeriesId,
      pageSize: 100,
    });
    computeList.value["attrs" + s.SeriesId] = res2.Data || [];
    const res3 = await offerQueryApi({
      seriesId: s.SeriesId,
      pageSize: 100,
    });
    offerList.value["attrs" + s.SeriesId] = res3.Data || [];
  }
  const res4 = await customerQueryApi();
  customerList.value = res4.Data || [];
  // 按照排序，第一个优先级最高
  if (seriesList.value.length !== 0) {
    columns.value = attrsList.value["attrs" + seriesList.value[0].SeriesId];
    columnsConsist();
    invisibleColFilter();
    customeColSort();
  }
  const res1 = await brandQueryApi();
  brandList.value = res1.Data;
  await getSaleData();

  dataList.value.forEach(async (item) => {
    // item = setDefaultValue(item);
    if (!item.GateType) item.GateType = item.Field3;
    if (!item.Color) item.Color = item.Field4;
    item.OrderCode = await setOrderCode();
    for (let key in item) {
      columnCompute(item, key);
    }
  });
  loading.value = false;
}
async function addDataList(i = -1) {
  let obj = {};
  if (seriesList.value.length !== 0) {
    obj.SeriesId = seriesList.value[0].SeriesId;
    obj.SeriesName = seriesList.value[0].SeriesName;
  } else {
    obj.SeriesId = 0;
  }

  obj.unsaved = true; // 用于在循环请求添加订单的时候判断是否是用户刚刚新增的数据
  obj.OrderCode = await setOrderCode(1);
  obj = setDefaultValue(obj);
  if (i !== -1) {
    dataList.value.splice(i, 0, obj);
  } else {
    dataList.value.push(obj);
  }
}
async function setOrderCode(type = 1) {
  // type = 1 —— 子单，2 —— 总单
  // 判断是否是已存在销售单的子单，然后给对应格式的OrderCode
  // 子单：YYMMDD-nnn-nn，总单：YYMMDD-nnn
  let no = "";
  if (type == 1) {
    let saleNo = saleOrderInfo.value.TOrderCode;
    let dayCode = dayjs().format("YYMMDD");
    // no = saleDataList.value
    //   .map((item) => item.TOrderCode)
    //   .filter((item) => item.includes(dayCode))
    no = dataList.value.map((item) => item.OrderCode).filter(Boolean);
    if (no.length !== 0) {
      no = no.sort().at(-1).split("-")[2];
      // no = saleNo.includes(dayCode)
      //   ? saleNo
      //   : dayCode + "-001" + "-" + String(+no + 1).padStart("2", "0");
      no = saleNo + "-" + String(+no + 1).padStart("2", "0");
    } else {
      no = saleNo?.includes(dayCode)
        ? saleNo + "-01"
        : dayCode + "-001" + "-01";
    }
  } else {
    let list = saleDataList.value;
    if (list.length !== 0) {
      no = list
        .map((item) => item.TOrderCode)
        .filter(Boolean)
        .sort()
        .at(-1);
    } else {
      const { TOrderCode } = await orderCodeApi();
      no = TOrderCode ? TOrderCode : "";
    }
    let dayCode = dayjs().format("YYMMDD");
    if (no.includes(dayCode)) {
      no =
        no.split("-")[0] +
        "-" +
        String(+no.split("-")[1] + 1).padStart("3", "0");
    } else {
      no = dayCode + "-001";
    }
  }
  // let flag = dataList.value.some((item) => !item.unsaved);
  // let no;
  // if (flag) {
  //   no = dataList.value
  //     .map((item) => item.OrderCode)
  //     .filter(Boolean)
  //     .sort()
  //     .at(-1)
  //     .split("-")[2];
  //   no =
  //     currentSaleRow.value.TOrderCode +
  //     "-" +
  //     String(+no + 1).padStart("2", "0");
  // } else {
  //   let saleNo = saleDataList.value
  //     .map((item) => item.TOrderCode)
  //     .filter(Boolean)
  //     .sort()
  //     .at(-1);
  //   let dayCode = dayjs().format("YYMMDD");
  //   // no = saleDataList.value
  //   //   .map((item) => item.TOrderCode)
  //   //   .filter((item) => item.includes(dayCode))
  //   no = dataList.value.map((item) => item.OrderCode).filter(Boolean);
  //   if (no.length !== 0) {
  //     no = no.sort().at(-1).split("-")[2];
  //     no = saleNo.includes(dayCode)
  //       ? saleNo
  //       : dayCode + "-001" + "-" + String(+no + 1).padStart("2", "0");
  //   } else {
  //     no = saleNo.includes(dayCode) ? saleNo : dayCode + "-001" + "-01";
  //   }
  // }
  return no;
}
function setDefaultValue(row) {
  columns.value.forEach((col) => {
    if (!row.SeriesId) {
      let res = seriesList.value.find((item) => item.SeriesName == row.Field1);
      if (res) row.SeriesId = res.SeriesId;
    }

    // 数量、长宽高因为前面合并被过滤，这里添加值需注意键名，以免计算属性匹配不到相应key导致公式运算报错
    if (col.AttrKeyName == "Count") {
    }

    // 无输入，且有设置默认值
    if (!row[col.AttrKeyName] && col.DefaultValue) {
      row[col.AttrKeyName] = col.DefaultValue;
    } else if (!row[col.AttrKeyName]) {
      row[col.AttrKeyName] = "";
    }
  });
  return row;
}
function computeAttrCalc(row, computeTarget, isOfferPrice = false) {
  let { SeriesId } = row;
  let formula = computeTarget.AttrValue.replace(/×/g, "*")
    .replace(/÷/g, "/")
    .replace(/（/g, "(")
    .replace(/）/g, ")")
    .replace(/【/g, "[")
    .replace(/】/g, "]");
  for (let key in row) {
    let attr = attrsList.value["attrs" + SeriesId].find(
      (attr) => attr.AttrKeyName == key
    );
    if (attr && attr.AttrName && !["Count"].includes(key)) {
      if (formula.includes(attr.AttrName)) {
        formula = formula.replaceAll(attr.AttrName, Number(row[key]) || 0);
      }
    }
  }
  // console.log("formula", formula);s
  if (/[\u4e00-\u9fa5]/g.test(formula)) {
    return ElMessage.error("计算属性计算失败，公式：" + formula);
  }
  console.log("computeTarget.AttrName", computeTarget, computeTarget.AttrName);
  try {
    row[getAttrKey(isOfferPrice ? "结算金额" : computeTarget.AttrName)] =
      evaluate(formula).toFixed(2);
  } catch (error) {
    ElMessage.error("计算出错：" + formula);
  }
}
// 將數量左-右、长宽厚合并到一起
function columnsConsist() {
  // columns.value = columns.value.filter(
  //   (col) =>
  //     ![
  //       "Count1",
  //       "Count2",
  //       "Height_Total",
  //       "Width_Total",
  //       "Tickness_Wall",
  //       "DoorHeader",
  //       "DoorPost",
  //       "AttatchUrl",
  //     ].includes(col.AttrKeyName)
  // );
  columns.value.splice(2, 0, {
    AttrId: createUniqueString(),
    AttrKeyName: "Count",
    AttrName: "数量",
    ColumnWidth: 50,
    AttrValue: "1",
    DefaultValue: "",
    FixType: 0,
    InputType: 1,
    InputType2: 0,
    IsVisible: true,
    SortIndex: 1,
  });

  columns.value.splice(2, 0, {
    AttrId: createUniqueString(),
    AttrKeyName: "specification",
    AttrName: "规格",
    ColumnWidth: 130,
    AttrValue: "1",
    DefaultValue: "",
    FixType: 0,
    InputType: 1,
    InputType2: 0,
    IsVisible: true,
    SortIndex: 1,
  });

  columns.value.splice(2, 0, {
    AttrId: createUniqueString(),
    AttrKeyName: "DoorHeaderPost",
    AttrName: "门头门柱",
    ColumnWidth: 90,
    AttrValue: "1",
    DefaultValue: "",
    FixType: 0,
    InputType: 1,
    InputType2: 0,
    IsVisible: true,
    SortIndex: 1,
  });
}
function invisibleColFilter() {
  // let maxKey = 0;
  // let max = 0;
  // for (let key in attrsList.value) {
  //   if (attrsList.value[key].length > max) {
  //     max = attrsList.value[key].length;
  //     maxKey = key;
  //   }
  // }
  // columns.value = attrsList.value[maxKey];

  // 如果所有产品系列都设置不显示则过滤该列
  columns.value = columns.value.filter((col) => {
    return Object.values(attrsList.value).some((attrs) => {
      let result = attrs.find((a) => a.AttrName == col.AttrName);
      if (!result) return true;
      return result.IsVisible;
    });
  });
}
function customeColSort() {
  let newColumns = [];
  customeSequence.forEach((key, index) => {
    let res = columns.value.find(
      (col) => customAttrKeyName(col.AttrName) == key
    );
    if (res) newColumns[index] = res;
  });
  newColumns = newColumns.concat(
    columns.value.filter(
      (col) => !customeSequence.includes(customAttrKeyName(col.AttrName))
    )
  );
  columns.value = newColumns;
}
const remove = function (array, val) {
  const index = array.indexOf(val);
  if (index > -1) {
    array.splice(index, 1);
    return true;
  }
  return false;
};
const prevTableHeight = ref(0);
const newTableHeight = ref(0);
// 展开行重新计算元素高度
watch(
  () => prevTableHeight.value,
  (val) => {
    nextTick(() => {
      newTableHeight.value = tableRef.value.$el.offsetHeight;
      computedHeight.value += newTableHeight.value - prevTableHeight.value;
    });
  }
);

watch(
  () => attachedPictureList.value,
  () => {
    if (attachedPictureList.value.every((e) => e.src)) {
      attachedPictureList.value.push({ col: "", src: "" });
    }
  },
  {
    deep: true,
  }
);
watch(
  () => route.path,
  (val, oldVal) => {
    if (val == "/order/orders" && oldVal == "/order/input") {
      getData();
    }
  }
);
const expandOpen = async (row, expand) => {
  prevTableHeight.value = tableRef.value.$el.offsetHeight;
  if (!remove(expandedRowKeys.value, row.AttrId)) {
    expandedRowKeys.value.push(row.AttrId);
  }
};
function sortData() {
  dataList.value = dataList.value.sort((item1, item2) => {});
}
function cellClick(row, curIndex, columnKey) {
  currentTableIndex = curIndex;
  //直接整行激活，自定义切换光标再处理tab键会让我很难办
  for (let key in row) {
    if (key.includes("Selected")) {
      row[key] = !row[key];
    }
  }
  setTimeout(() => {
    document.querySelector(`#input-${curIndex}${columnKey}`).focus();
  });

  // row[columnKey + "Selected"] = !row[columnKey + "Selected"];
}
function clickEvent() {}
function focusEvent(row, index, columnKey) {
  currentColumnKey.value = columnKey;
  row[columnKey + "_old"] = row[columnKey];
  // 如果字段包含在计算公式中则给用户冒泡提示
  if (columnKey) {
    let computes = computeList.value["attrs" + row.SeriesId].filter(
      (c) =>
        c.AttrValue.includes(orderAttrsMap2[columnKey]) ||
        c.AttrName == orderAttrsMap2[columnKey]
    );
    let offers = offerList.value["attrs" + row.SeriesId].filter((c) => {
      // c.AttrValue.includes(orderAttrsMap2[columnKey]) ||
      // c.AttrName == orderAttrsMap2[columnKey]
      if (columnKey == "Money_Settlement") {
        return c.AttrName == row.Settlement;
      } else {
        return (
          c.AttrName == row.Settlement &&
          c.AttrValue.includes(orderAttrsMap2[columnKey])
        );
      }
    });
    let tempComputes = [],
      tempOffers = [];
    computes.forEach((item) => {
      tempComputes.push({
        target: item.AttrName,
        formula: item.AttrValue,
        formulaEles: splitFormulaElements(item.AttrValue),
        targetValue: dataList.value[index][getAttrKey(item.AttrName)],
      });
    });
    offers.forEach((item) => {
      tempOffers.push({
        target: item.AttrName,
        formula: item.AttrValue,
        formulaEles: splitFormulaElements(item.AttrValue),
        targetValue: dataList.value[index][getAttrKey(item.AttrName)],
      });
    });

    if (computes.length !== 0 || offers.length !== 0) {
      currentInput.value = index + columnKey;
      popoverVisible.value = true;
      allowDisappear.value = false;
      popoverInfo.computes = tempComputes;
      popoverInfo.offers = tempOffers;
    } else {
      allowDisappear.value = true;
    }
  }
}
function changeEvent(row, curIndex, columnKey) {
  row.unsaved = true;
  columnCompute(row, columnKey);
}

//输入框失去焦点触发,此处用提示框提示修改
function blurEvent(row, curIndex, columnKey) {
  allowDisappear.value = true;
  if (row[columnKey] !== row[columnKey + "_old"]) {
    // 发送请求 将数据保存到服务器
    // ElMessage({
    //   message: "修改成功",
    //   type: "success",
    //   duration: 1000,
    // });
    columnCompute(row, columnKey);
  }
}
function columnCompute(row, columnKey) {
  // 存在于计算属性的公式中进入计算
  let computeTargetList = computeList.value["attrs" + row.SeriesId].filter(
    (c) => c.AttrValue.includes(orderAttrsMap2[columnKey])
  );
  computeTargetList.forEach((target) => {
    computeAttrCalc(row, target);
  });
  popoverInfo.computes.forEach((item) => {
    item.targetValue = row[getAttrKey(item.target)];
  });

  // 存在于报价方式的公式中进入计算
  let offerTargetList = offerList.value["attrs" + row.SeriesId].filter(
    (c) => {
      if (columnKey == "Money_Settlement") {
        return c.AttrName == row.Settlement;
      } else {
        return (
          c.AttrName == row.Settlement &&
          c.AttrValue.includes(orderAttrsMap2[columnKey])
        );
      }
    }
    // c.AttrName == orderAttrsMap2[columnKey] ||
  );
  offerTargetList.forEach((target) => {
    // target.AttrName = "结算金额";
    computeAttrCalc(row, target, true);
  });
  popoverInfo.offers.forEach((item) => {
    item.targetValue = row.Money_Settlement;
  });
}
// const vFocus = {
//   mounted(el) {
//     el.querySelector("input").focus();
//   },
// };
function keyupEvent(e, row, curIndex, columnKey) {
  if (e.keyCode == 38) {
    //按上键
    //首行判断
    if (curIndex == 0) {
      return;
    }
    currentTableIndex = curIndex - 1;
    // document.querySelector(`#input-${curIndex}${columnKey}`).blur();
    for (let key in dataList.value[curIndex]) {
      if (!key.includes("_old") && !key.includes("Selected")) {
        let dom = document.querySelector(`#input-${curIndex}${key}`);
        if (dom) dom.blur();
      }
    }
    setTimeout(() => {
      document.querySelector(`#input-${curIndex - 1}${columnKey}`).focus();
    });
  } else if (e.keyCode == 40) {
    if (curIndex == dataList.value.length - 1) {
      //向下键
      //末行判断
      return;
    }
    currentTableIndex = curIndex + 1;
    for (let key in dataList.value[curIndex]) {
      if (!key.includes("_old") && !key.includes("Selected")) {
        let dom = document.querySelector(`#input-${curIndex}${key}`);
        if (dom) dom.blur();
      }
    }
    setTimeout(() => {
      document.querySelector(`#input-${curIndex + 1}${columnKey}`).focus();
    });
  }
}
function selectEvent(row, curIndex, columnKey) {
  if (columnKey == "Settlement") {
    columnCompute(row, "Money_Settlement");
  }
}
function selectKeyJump(e, row, curIndex, columnKey) {
  // document.querySelector(`#input-${curIndex + 1}${columnKey}`).keydow
}
const testAttatchUrl = [
  "https://tse1-mm.cn.bing.net/th/id/OIP-C.fIWwD8_nzVDdch5N9EJfCwHaG6?rs=1&pid=ImgDetMain",
  "https://tse1-mm.cn.bing.net/th/id/OIP-C.fIWwD8_nzVDdch5N9EJfCwHaG6?rs=1&pid=ImgDetMain",
  "https://tse1-mm.cn.bing.net/th/id/OIP-C.fIWwD8_nzVDdch5N9EJfCwHaG6?rs=1&pid=ImgDetMain",
  "https://tse1-mm.cn.bing.net/th/id/OIP-C.fIWwD8_nzVDdch5N9EJfCwHaG6?rs=1&pid=ImgDetMain",
];
function handleImageClick(url) {
  window.open(url, "_blank");
}
function orderCellContextClick(e) {
  e.preventDefault();
  showMenu(e);
}
const ContextMenu = function (options) {
  // 唯一实例
  let instance;

  // 创建实例方法
  // function createMenu() {
  //   // todo
  // }

  return {
    // 获取实例的唯一方式
    getInstance: function () {
      if (!instance) {
        instance = createMenu(options);
      }
      return instance;
    },
  };
};
function showMenu(e) {
  const menus = menuSinglton.getInstance();
  menus.style.top = `${e.clientY}px`;
  menus.style.left = `${e.clientX}px`;
  menus.style.display = "block";
  if (e.clientY + menus.clientHeight > window.innerHeight) {
    let chazhi = e.clientY + menus.clientHeight - window.innerHeight;
    menus.style.top = `${e.clientY - chazhi - 10}px`;
  }
}
function hideMenu(e) {
  const menus = menuSinglton.getInstance();
  menus.style.display = "none";
}
document.addEventListener("click", hideMenu);
function createMenu(options) {
  const ul = document.createElement("ul");
  ul.classList.add("custom-context-menu");
  const { menus } = options;
  if (menus && menus.length > 0) {
    for (let menu of menus) {
      const li = document.createElement("li");
      li.textContent = menu.name;
      li.onclick = menu.onClick;
      ul.appendChild(li);
    }
  }
  const body = document.querySelector("body");
  body.appendChild(ul);
  return ul;
}
const menuSinglton = ContextMenu({
  menus: [
    {
      name: "打印销售单",
      onClick: function (e) {},
    },
    {
      name: "提交生产",
      onClick: function (e) {},
    },
    {
      name: "撤回",
      onClick: function (e) {},
    },
    {
      name: "详情页编辑",
      onClick: function (e) {},
    },
    {
      name: "删除销售单",
      onClick: function (e) {},
    },
    {
      name: "复制本单",
      onClick: function (e) {},
    },
    {
      name: "查看日志",
      onClick: function (e) {},
    },
  ],
});
const dividerActive = ref(false);
const startMove = ref(0);
const verticalMove = ref(0);
const lastVerticalMove = ref(0); //专门用于计算页面滚动距离加给鼠标移动差值
const computedHeight = ref(0);
const tableHeight = ref(window.outerHeight * 0.3);
const presentVerticalMove = ref(0); // 专门用于判断鼠标移动方向
function holdDown(e) {
  // 初始化的时候computedHeight莫名小于盒子的内高导致拖不动
  computedHeight.value = document.querySelector(".table-wrapper").clientHeight;

  dividerActive.value = true;
  startMove.value = e.clientY;
  document.addEventListener("mouseup", holdUp);
  document.addEventListener("mousemove", holding);
}
function holdUp() {
  dividerActive.value = false;
  computedHeight.value = computedHeight.value + verticalMove.value;
  tableHeight.value += verticalMove.value;
  verticalMove.value = 0;
  document.removeEventListener("mouseup", holdUp);
  document.removeEventListener("mousemove", holding);
}
function holding(e) {
  let sHeight = document.querySelector(".dashboard-editor-container").scrollTop;
  presentVerticalMove.value = e.clientY - startMove.value;
  // console.log(lastVerticalMove.value, presentVerticalMove.value)
  if (lastVerticalMove.value - presentVerticalMove.value > 0) {
    if (
      verticalMove.value + computedHeight.value <
        tableRef.value.$el.offsetHeight + 100 ||
      tableHeight.value + verticalMove.value < window.outerHeight * 0.3
    )
      return;
  }
  lastVerticalMove.value = verticalMove.value;
  if (dividerActive.value) {
    verticalMove.value = e.clientY - startMove.value;
  }
}
function addRowStyle({ row }) {
  let style = {
    background: "#ffe6e1",
  };
  style.background = generateHexColor(row.SeriesId);
  return style;
}
function onProductChange() {}
function openPictureModal(i, key) {
  dataList.value[i].pictureSelectKey = key;
  pictureList.value = dataList.value[i][key];
  pictureOpen.value = true;
}
async function pictureConfirm() {
  pictureOpen.value = false;
  dataList.value.forEach(async (item) => {
    if (item.pictureSelectKey) {
      item[item.pictureSelectKey] = pictureList.value
        .map((it) => it.url)
        .join(",");
      for (let i = 0; i < pictureList.value.length; i++) {
        if (pictureList.value[i].origin instanceof File) {
          let file = pictureList.value[i].origin;
          const result = await uploadImg({ img: file, Name: file.name });
          pictureList.value[i].url = result.name;
        }
      }
      item[item.pictureSelectKey] = pictureList.value
        .map((it) => it.url)
        .join(",");
      delete item.pictureSelectKey;
    }
    item.unsaved = true;
  });
}
function handleTableScroll(behavior) {
  const wrapRef = tableRef.value.scrollBarRef.wrapRef;
  switch (behavior) {
    case "left":
      wrapRef.scrollTo({
        left: wrapRef.scrollLeft - 500,
        behavior: "smooth",
      });
      break;
    case "right":
      wrapRef.scrollTo({
        left: wrapRef.scrollLeft + 500,
        behavior: "smooth",
      });
      break;
    case "d-left":
      tableScrollToColumn(tableRef.value, 1);
      break;
    case "d-right":
      tableScrollToColumn(tableRef.value, columns.value.length);
      break;
    case "center":
      wrapRef.scrollTo({
        left: (wrapRef.scrollWidth - wrapRef.clientWidth) / 2,
        behavior: "smooth",
      });
      break;
    default:
  }
}

function handleColSelect(val) {
  if (val) {
    let i = columns.value.findIndex((col) => col.AttrName == val);
    tableScrollToColumn(tableRef.value, i);
  }
}
async function pasteEvent(event) {
  // 输出事件对象的clipboardData属性，如下图，数据存储在对象中，但是直接打开是看不到的，只有输出event.clipboardData对象的某个属性或方法才可以看到
  // 获取文本值
  event.clipboardData.getData("text");
  // 获取图片
  // 读取到图片对象
  let file = event.clipboardData.files[0];
  // 判断类型
  if (!file || !/^image\/[jpeg|png|gif|jpg]/.test(file.type)) {
    ElMessage.warning("粘贴失败，未找到图片");
    return;
  }
  const res = await uploadImg({ img: file, Name: file.name });
  attachedPictureList.value[currentImgIndex.value].src = res.name;

  const [row] = tableRef.value.getSelectionRows();
  row.AttatchUrl = attachedPictureList.value.map((e) => e.src).join(",");
  row.unsaved = true;

  ElMessage.success("粘贴成功");

  // // 读取成base64
  // let reader = new FileReader();
  // reader.readAsDataURL(file);
  // // 监听读取完成
  // reader.onload = function () {
  //   let base64 = reader.result;
  //   const blob = base64ToBlob(base64);
  //   attachedPictureList.value[currentImgIndex.value].src =
  //     URL.createObjectURL(blob);

  //   const [row] = tableRef.value.getSelectionRows();
  //   row.AttatchUrl = attachedPictureList.value.map((e) => e.src).join(",");

  //   ElMessage.success("粘贴成功");
  // };
}
function registerPaste() {
  // for (let item of document.querySelectorAll("[id^=abc]")) {
  //   item.removeEventListener("paste", pasteEvent);
  //   item.addEventListener("paste", pasteEvent);
  // }
  // document.documentElement.removeEventListener("paste", pasteEvent, true);
  // document.documentElement.addEventListener("paste", pasteEvent);
  // document.documentElement.onpaste = pasteEvent;
}

async function pasteImage(e, item, index) {
  // var event = new MouseEvent("contextmenu", {
  //   bubbles: true,
  //   cancelable: true,
  //   view: window,
  //   button: 2, // 右键
  // });
  // const input = document.createElement("input");
  // document.body.append(input);
  // input.dispatchEvent(event);
  if (tableRef.value.getSelectionRows().length !== 1) {
    return ElMessage.warning("请先勾选一条子单");
  }

  currentImgIndex.value = index;
  if (e.button == 0) {
    imgUploader.value.click();
    return false;
  }
  // if (e.button == 2)
  //   try {
  //     e.target.focus();
  //   } catch (error) {
  //     ElMessage.error(error);
  //   }
}
function handlePreviewImg(url) {
  window.open(url, "_blank");
}
function handleDeleteImg(i) {
  currentImgIndex.value = -1;

  attachedPictureList.value.splice(i, 1);
  const [row] = tableRef.value.getSelectionRows();
  row.AttatchUrl = attachedPictureList.value.map((e) => e.src).join(",");
}
function toDetailRecord() {
  orderStore.setOrderData(dataList.value);
  orderStore.setSaleOrderData(saleDataList.value);
  orderStore.setSeriesData(seriesList.value);
  orderStore.setCurrentSaleRow(currentSaleRow.value);
  orderStore.setAttrsData(attrsList.value);
  orderStore.setComputeData(computeList.value);
  orderStore.setOfferData(offerList.value);
  orderStore.setColumns(columns.value);
  orderStore.setSaleInfo({
    customerName: customer.value,
    PartnerBrand: brandName.value,
    deliveryTime: deliveryTime.value,
  });
  router.push({
    path: "./input",
  });
}
/**
 * 从不同产品类型的相同列的列宽度设置中取最大值作为该列实际列宽
 */
function getHighColWidth(attrName) {
  //   attrName,
  //   Math.min(
  //     ...seriesList.value.map(({ SeriesId }) => {
  //       return (
  //         attrsList.value["attrs" + SeriesId].find(
  //           (a) => a.AttrName == attrName
  //         )?.ColumnWidth || 0
  //       );
  //     })
  //   )
  // );
  if (attrName && ["数量", "规格", "门头门柱"].includes(attrName)) {
    return +columns.value.find(
      (item) => customAttrKeyName(item.AttrName) == attrName
    ).ColumnWidth;
  }
  return Math.min(
    ...seriesList.value.map(({ SeriesId }) => {
      return (
        attrsList.value["attrs" + SeriesId].find((a) => a.AttrName == attrName)
          ?.ColumnWidth || 0
      );
    })
  );
}
function getSpecificSetting(seriesId, AttrKeyName, settingName) {
  let series = seriesList.value.find((s) => s.SeriesId == seriesId);
  if (series) {
    let p = attrsList.value["attrs" + seriesId].find(
      (item) => item.AttrKeyName == AttrKeyName
    );
    return p && p[settingName];
  }
  return "";
}
function handleRowCheckBox(rows) {
  if (rows.length !== 1) {
    attachedPictureList.value = [{ col: "", src: "" }];
    return;
  }
  attachedPictureList.value = rows[0].AttatchUrl.split(",")
    .filter(Boolean)
    .map((item) => ({ src: item }));
}
function handlePaste(e, index) {
  if (tableRef.value.getSelectionRows().length !== 1) {
    return ElMessage.warning("请先勾选一条子单");
  }
  currentImgIndex.value = index;
  pasteEvent(e);
}
async function handleAdd() {
  await addDataList();
  nextTick(() => {
    tableRef.value.scrollBarRef.wrapRef.scrollTo({
      top: tableRef.value.scrollBarRef.wrapRef.scrollHeight,
      behavior: "smooth",
    });
  });
}
// 点击新增总单，创建一条空的销售单
async function majorAdd() {
  if (!throttle.value) {
    clearTimeout(throttleTimer);
    throttleTimer.value = setTimeout(() => {
      throttle.value = true;
    }, 5000);
    return ElMessage.warning("请求频率过高，请稍后再试");
  }
  throttleTimer.value = setTimeout(() => {
    throttle.value = true;
  }, 5000);
  // if (!customer.value) {
  //   ElMessage.warning("请选择客户");
  //   return;
  // }
  // if (!brandName.value) {
  //   ElMessage.warning("请选择代理品牌");
  //   return;
  // }
  // if (!deliveryTime.value) {
  //   ElMessage.warning("请选择交货时间");
  //   return;
  // }
  // if (
  //   typeof deliveryTime.value == "string" &&
  //   deliveryTime.value.includes("Date(")
  // ) {
  //   deliveryTime.value = timeStampFormatter(deliveryTime.value);
  //   if (deliveryTime.value == "无") {
  //     ElMessage.warning("交货时间格式不正确");
  //     return;
  //   }
  // }
  throttle.value = false;
  // 判断是否存在正在编辑的销售单，保存
  if (saleOrderInfo.value.TOrderCode) {
    await handleSave();
    saleOrderInfo.value = {};
    dataList.value = [];
  }

  let createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");

  loading.value = true;
  saleOrderInfo.value.TOrderCode = await setOrderCode(2);
  await addDataList();
  // let attrList = [];
  // for (let key in dataList.value[0]) {
  //   let item = dataList.value[0];
  //   if (item.unsaved && item[key] && !["id", "unsaved"].includes(key)) {
  //     attrList.push({ Name: key, Value: String(item[key]) });
  //     if (attrList.at(-1).Name == "SeriesName") {
  //       attrList.at(-1).Name = "Field1";
  //     }
  //     delete item.unsaved;
  //   }
  // }

  let series = seriesList.value.find((e) => e.SeriesId == seriesId.value);
  await saleOrderAddEmptyApi({
    TOrderCode: saleOrderInfo.value.TOrderCode,
    CustomerName: customer.value,
    BrandName: brandName.value,
    TOrderEDate: deliveryTime.value,
    SeriesName: (series && series.SeriesName) || "",
  });
  await getSaleData();
  loading.value = false;
}
// 增加到销售单列表操作
async function handleSave() {
  // if (!customer.value) {
  //   ElMessage.warning("请选择客户");
  //   return;
  // }
  // if (!brandName.value) {
  //   ElMessage.warning("请选择代理品牌");
  //   return;
  // }
  // if (!seriesId.value) {
  //   ElMessage.warning("请选择产品类型");
  //   return;
  // }
  // if (!deliveryTime.value) {
  //   ElMessage.warning("请选择交货时间");
  //   return;
  // }
  if (
    typeof deliveryTime.value == "string" &&
    deliveryTime.value.includes("Date(")
  ) {
    deliveryTime.value = timeStampFormatter(deliveryTime.value);
    if (deliveryTime.value == "无") {
      ElMessage.warning("交货时间格式不正确");
      return;
    }
  }

  loading.value = true;
  let AttrLists = [];
  dataList.value.map((item) => {
    let AttrList = [];
    for (let key in item) {
      // if (item.unsaved && item[key] && !["id", "unsaved"].includes(key)) {
      if (item[key] && !["id", "unsaved"].includes(key)) {
        AttrList.push({ Name: key, Value: String(item[key]) });
        if (AttrList.at(-1).Name == "SeriesName") {
          AttrList.at(-1).Name = "Field1";
        }
      }
    }
    if (item.unsaved)
      // delete item.unsaved;
      AttrLists.push(AttrList);
    else AttrLists.push([]);
  });
  //   "AttrLists[i]",
  //   AttrLists,
  //   dataList.value.map((item) => item.OrderCode)
  // );
  let createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
  for (let i = 0; i < dataList.value.length; i++) {
    if (AttrLists[i].length !== 0) {
      await saleOrderAddApi({
        OrderId: dataList.value[i].OrderId || 0,
        OrderCode: dataList.value[i].OrderCode,
        CustomerName: customer.value,
        BrandName: brandName.value,
        CreateTime: createTime,
        OrderTime: deliveryTime.value,
        SeriesName: seriesList.value.find((e) => e.SeriesId == seriesId.value)
          .SeriesName,
        AttrList: AttrLists[i],
      });
    }
  }
  // 保存总单信息
  let series = seriesList.value.find((e) => e.SeriesId == seriesId.value);
  await saleOrderAddEmptyApi({
    TOrderId: saleOrderInfo.value.TOrderId,
    TOrderCode: saleOrderInfo.value.TOrderCode,
    CustomerName: customer.value,
    BrandName: brandName.value,
    TOrderEDate: deliveryTime.value,
    SeriesName: (series && series.SeriesName) || "",
  });

  await getSaleData();

  // 如果是新增销售单先存本地
  // if (!currentSaleRow.value.TOrderId) {
  //   let TOrderCode = dataList.value[0].OrderCode.split("-");
  //   TOrderCode = TOrderCode[0] + "-" + TOrderCode[1];
  //   tempDataList = dataList.value;
  //   saleDataList.value.push({
  //     unsaved: true,
  //     TOrderCode,
  //     OrderCodeStr: dataList.value.map((item) => item.OrderCode).join(","),
  //     TField1: "非标门系列",
  //     CustomerName: customer.value,
  //     TSubCustomerNames: dataList.value
  //       .map((item) => item.SubCustomerName)
  //       .join(","),
  //     TOrderPDate: createTime,
  //     TPrice: 0,
  //     TPieceCount: 0,
  //     SalesmanName: "",
  //     Status: false,
  //     TOrderId:
  //       +saleDataList.value
  //         .map((item) => item.TOrderId)
  //         .sort()
  //         .at(-1) + 1,
  //   });
  //   submitTableRef.value.toggleRowSelection(saleDataList.value.at(-1));
  // }
  // tempSaleDataList = saleDataList.value;
  // setTimeout(async () => {
  //   const res3 = await saleOrderQueryApi({
  //     BeginDate: saleDate.value[0],
  //     EndDate: saleDate.value[1],
  //   });
  //   saleDataList.value = res3.Data || [];
  //   if (currentSaleRow.value.TOrderId) {
  //     const res = await saleOrderDetailApi(currentSaleRow.value.TOrderId);
  //     // dataList.value = res.OrderList || [];
  //     // dataList.value.forEach((item) => {
  //     //   item = setDefaultValue(item);
  //     //   for (let key in item) {
  //     //     columnCompute(item, key);
  //     //   }
  //     // });
  //     customer.value = res.TOrderInfo.CustomerName;
  //     brandName.value = res.TOrderInfo.TField2;
  //     deliveryTime.value = res.TOrderInfo.DeliveryTime;
  //     saleOrderInfo.value = res.TOrderInfo;
  //     currentSaleRow.value = res.TOrderInfo;
  //     submitTableRef.value.clearSelection();
  //     submitTableRef.value.toggleRowSelection(
  //       saleDataList.value.find(
  //         (e) => e.TOrderId == currentSaleRow.value.TOrderId
  //       ),
  //       true
  //     );
  //   }
  // }, 1500);
  ElMessage.success("保存成功");
  loading.value = false;
}
function handleDelete() {
  ElMessageBox.confirm("确定清空吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      saleOrderInfo.value = {};
      dataList.value = [];
      customer.value = "";
      brandName.value = "";
      seriesId.value = "";
      deliveryTime.value = "";
    })
    .catch(() => {});
}
function handleSubmit() {
  // let submitedRows = tableRef.value.getSelectionRows();
  // if (submitedRows.length == 0) {
  //   ElMessageBox.confirm("确认全部提交？", "提示", {
  //     type: "warning",
  //   }).then(() => {
  //     dataList.value.forEach((item) => {
  //       item.submited = true;
  //     });
  //     ElMessage.success("提交成功");
  //   });
  // } else {
  //   submitedRows.forEach((item) => {
  //     item.submited = true;
  //   });
  //   ElMessage.success("提交成功");
  // }
}
async function handlePrint() {
  const selectionRows = submitTableRef.value.getSelectionRows();
  if (selectionRows.length == 1) {
    let res = await customerQueryApi({
      keyStr: currentSaleRow.value.CustomerName,
    });
    res = res.Data || [];
    const customerInfo = res[0] || {};
    const routeData = router.resolve({
      path: "./print",
      query: {
        data: JSON.stringify(dataList.value),
        images: JSON.stringify(dataList.value[0].AttatchUrl.split(",")),
        customer: JSON.stringify({
          name: customer.value,
          phone: customerInfo.Mobile || "",
        }),
        saleOrderInfo: JSON.stringify(saleOrderInfo.value),
      },
    });
    window.open(routeData.href, "_blank");
    // router.push({
    //   path: "./print",
    //   query: {
    //     data: JSON.stringify(selectionRows),
    //     images: JSON.stringify(attachedPictureList.value),
    //     customer: customer.value,
    //   },
    // });
  } else {
    ElMessage.warning("请勾选一条需要打印的订单");
  }
}
function handleClick() {}
function syncOrderAttrs() {
  ElMessageBox.confirm("是否将订单属性最新设置同步到输单表格？", "提示", {
    type: "warning",
  })
    .then(async (res) => {
      await getData();
    })
    .catch((err) => {});
}
// 销售单表格行点击事件
async function handleRowClick(row) {
  if (
    currentSaleRow.value.TOrderCode == row.TOrderCode &&
    submitTableRef.value.getSelectionRows().length == 1
  ) {
    submitTableRef.value.clearSelection();
  } else {
    submitTableRef.value.clearSelection();
    submitTableRef.value.toggleRowSelection(row);
  }
  if (submitTableRef.value.getSelectionRows().length == 1) {
    currentSaleRow.value = row;
    if (dataList.value.some((item) => item.unsaved)) {
      if (unsavedWarnOff.value)
        // await ElMessageBox.confirm(
        //   "有新增订单未保存，退出页面后其数据将会丢失，请及时保存",
        //   "警告",
        //   {
        //     type: "warning",
        //     showCancelButton: false,
        //   }
        // );
        unsavedWarnOff.value = true;
      // 如果全是未保存的数据，也就是总单都是未保存状态
      // 则新增
      if (dataList.value.some((item) => !item.unsaved))
        saleDataList.value.push({
          OrderCode:
            "未保存-" +
            (saleDataList.value.filter((s) => s.unsaved).length + 1),
          OrderList: dataList.value,
        });
      else {
        // unsavedSaleList
        // 如果是已经存在的销售单，则添加到已有销售单的子单的后面
        // 有点麻烦，先不处理
      }
    }
    loading.value = true;
    let res;
    if (row.unsaved) {
      await getSaleData();
      await repeatGetSaleData();
      res = await saleOrderDetailApi(saleDataList.value.at(-1).TOrderId);
      await repeatGetSaleDetail(res);
    } else {
      res = await saleOrderDetailApi(row.TOrderId);
    }
    // 获取销售单详情
    dataList.value = res.OrderList || [];
    dataList.value.forEach((item) => {
      if (!item.GateType) item.GateType = item.Field3;
      if (!item.Color) item.Color = item.Field4;
      item = setDefaultValue(item);
      for (let key in item) {
        columnCompute(item, key);
      }
    });
    customer.value = res.TOrderInfo.CustomerName;
    brandName.value = res.TOrderInfo.TField2;
    seriesId.value = seriesList.value.find(
      (e) => e.SeriesName == res.TOrderInfo.TField1
    )?.SeriesId;
    deliveryTime.value = timeStampFormatter(res.TOrderInfo.TOrderEDate);
    saleOrderInfo.value = res.TOrderInfo;

    if (dataList.value.length == 0) {
      await addDataList();
    }

    loading.value = false;
  } else {
    dataList.value = [];
    currentSaleRow.value = {};
    saleOrderInfo.value = {};
    customer.value = "";
    brandName.value = "";
    seriesId.value = "";
    deliveryTime.value = "";
  }
}
function handleRowSelect(rows) {
  if (rows.length == 0) {
    dataList.value = [];
    currentSaleRow.value = {};
    saleOrderInfo.value = {};
    customer.value = "";
    brandName.value = "";
    seriesId.value = "";
    deliveryTime.value = "";
  }
}
async function repeatGetSaleData() {
  if (tempSaleDataList.length == saleDataList.value.length) return;
  else {
    await getSaleData();
    repeatGetSaleData();
  }
}

async function repeatGetSaleDetail(res) {
  if (res.OrderList.length == tempDataList.length) return;
  else {
    let res2 = await saleOrderDetailApi(res.TOrderInfo.TOrderId);
    repeatGetSaleDetail(res2);
  }
}
async function getSaleData() {
  const res3 = await saleOrderQueryApi({
    BeginDate: saleDate.value[0],
    EndDate: saleDate.value[1],
  });
  saleDataList.value = res3.Data || [];

  // 按单号降序排序，新的在最前面
  saleDataList.value = saleDataList.value.sort((a, b) =>
    b.TOrderCode.localeCompare(a.TOrderCode)
  );
  // submitTableRef.value.clearSelection();
  saleDataList.value.forEach((item) => {
    item.OrderCodeStr = "";
  });

  // if (
  //   !saleDataList.value
  //     .map((item) => item.TOrderId)
  //     .includes(currentSaleRow.value.TOrderId)
  // ) {
  //   currentSaleRow.value = {};
  //   dataList.value = [];
  //   saleOrderInfo.value = {};
  //   customer.value = "";
  //   brandName.value = "";
  //   deliveryTime.value = "";
  // }
}
function handleDeleteUnsaved() {
  let ids = submitTableRef.value
    .getSelectionRows()
    .map((item) => item.TOrderId);
  if (ids.length == 0) return;
  ElMessageBox.confirm("确认删除?", "提示", {
    type: "warning",
  })
    .then(async (res) => {
      await saleOrderRemoveApi(ids);
      await getSaleData();
      saleOrderInfo.value = {};
      dataList.value = [];
      customer.value = "";
      brandName.value = "";
      deliveryTime.value = "";
      seriesId.value = "";
      ElMessage.success("删除成功");
      submitTableRef.value.clearSelection();
    })
    .catch((err) => {});
}
function customAttrKeyName(name) {
  switch (name) {
    case "包边名称":
      return "包边";
    case "工艺名称":
      return "结构";
    case "气窗款式":
      return "气窗";
    case "门框材料":
      return "门框";
    case "门面材料":
      return "门面";
    case "锁具名称":
      return "锁具";
    case "拉手名称":
      return "拉手";
    case "下档类型":
      return "下档";
    case "铰链名称":
      return "铰链";
    case "门高":
      return "含中下档高";
    case "结算金额":
      return "金额";
    default:
      return name;
  }
}
async function handleOperate(flag, index) {
  if (flag == "add") {
    await addDataList(index + 1);
  } else {
    ElMessageBox.confirm("确认删除吗？", "提示", {
      type: "warning",
    })
      .then(async (res) => {
        let row = dataList.value[index];
        if (!row.unsaved) {
          await orderRemoveApi(row.OrderId);
          dataList.value.splice(index, 1);
        } else {
          dataList.value.splice(index, 1);
        }
      })
      .catch((err) => {
        if (err !== "cancel") ElMessage.error("删除失败：" + err);
      });
  }
}
</script>
<style lang="scss">
.dashboard-editor-container {
  /* padding: 16px; */
  /* background-color: rgb(240, 242, 245); */
  position: relative;
  overflow-y: scroll;
  max-height: calc(100vh - 84px);
}

.custom-context-menu {
  display: none;
  list-style: none;
  position: fixed;
  z-index: 999;
  font-size: 13px;
  background: #fefefe;
  border: 1px solid #ccc;
  margin: 0;
  padding: 0;
  box-shadow: 3px 3px 6px #666;
  color: #444;

  li {
    box-sizing: border-box;
    padding: 4px 24px;
  }

  li:nth-child(n + 1) {
    // margin-top: 8px;
    cursor: pointer;
  }

  li:hover {
    transition: background-color 0.2s;
    background-color: #eee;
  }
}

.layout-divider {
  width: 100%;
  height: 3px;
  background: gray;
  margin: 10px 0;
  cursor: row-resize;

  &-icon {
    width: 1.2em;
    height: 1.2em;
    color: white;
    background: #3e9eff;
    padding: 0.1em;
    border-radius: 5px;
    transform: translateY(-50%);
  }
}

.divider-active {
  background: black;

  &-icon {
    border: 1px solid black;
  }
}

.table-wrapper {
  margin-bottom: 30px;
}

.scroll-status-bar::before {
  content: "";
  position: absolute;
  bottom: 0;
  left: v-bind(scrollBarLeft);
  width: 10%;
  height: 3px;
  border-radius: 100px;
  background: #409eff;
}

.my-btn-hover:hover {
  background: #25a87c !important;
  color: white;
}

.el-input__wrapper {
  padding: 1px 5px;
}

.el-select__wrapper {
  padding: 1px 5px;
}

.el-table--default .cell {
  padding: 0 1px;
}

.el-form--inline .el-form-item {
  // display: inline-flex;
  margin-right: 22px;
  // vertical-align: middle;
}
</style>
